#include"EchoServer.h"

using std::cout;
using std::endl;

EchoServer::EchoServer(const std::string &ip, const uint16_t port, int threadNum, int workThreadNum):tcpserver_(ip, port, threadNum), threadPoll_(workThreadNum, "WORKS")
{
    tcpserver_.setnewconnectioncallback(std::bind(&EchoServer::HandleNewConnection, this, std::placeholders::_1));
    tcpserver_.setcloseconnectioncallback(std::bind(&EchoServer::HandleCloseConnection, this, std::placeholders::_1));
    tcpserver_.seterrorconnectioncallback(std::bind(&EchoServer::HandleErrorConnection, this, std::placeholders::_1));
    tcpserver_.setonmessagecallback(std::bind(&EchoServer::HandleMessage, this, std::placeholders::_1, std::placeholders::_2));
    tcpserver_.setsendcompletecallback(std::bind(&EchoServer::HandleSendComplete, this, std::placeholders::_1));
    tcpserver_.setepolltimeoutcallback(std::bind(&EchoServer::HandleEpollTimeOut, this, std::placeholders::_1));
}

EchoServer::~EchoServer()
{
}

void EchoServer::Start()
{
    tcpserver_.start();
}

void EchoServer::HandleNewConnection(std::shared_ptr<Connection>conn)
{
    cout << "EchoServer: New Connection Come in" << endl;
}

void EchoServer::HandleCloseConnection(std::shared_ptr<Connection>conn)
{
    cout << "EchoServer: Connection Close" << endl;
}

void EchoServer::HandleErrorConnection(std::shared_ptr<Connection>conn)
{
    cout << "EchoServer: Connection Error" << endl;
}

void EchoServer::HandleMessage(std::shared_ptr<Connection>conn, std::string& message)
{
    // cout << "EchoServer: Handle Message" << endl;
    // 把业务处理添加到线程池中
    threadPoll_.AddTask(std::bind(&EchoServer::OnMessage, this, conn, message));
    /*
    补充一点：这里只能使用 std::bind，不能直接使用lambda表达式,
    例如：threadPoll_.AddTask([&]{ 
            message = "reply:" + message;
            conn->send(message.data(), message.size());
        });
        但 message 是引用传递的，等到时候处理的时候会报错空指针或者内存越界
    */
}

void EchoServer::HandleSendComplete(std::shared_ptr<Connection>conn)
{
    // cout << "EchoServer: Send Complete" << endl;
}

void EchoServer::HandleEpollTimeOut(EventLoop *loop)
{
    // cout << "EchoServer: Epoll Time Out" << endl;
}

void EchoServer::OnMessage(std::shared_ptr<Connection>conn, std::string &message)
{
    // ...这里对接收到的报文数据做逻辑处理
    message = "reply:" + message;

    //  将数据添加到发生缓冲区中，待监听到写事件时回调时发送
    conn->send(message.data(), message.size());
}
